package com.jsp.controller;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author wzm
 * @create 2023-11-08 14:34
 * project_name:web2310
 * @Description
 */
public class BaseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //执行子类的相关方法
        //根据请求路径获取需要执行的方法 http://localhost:8080/user/login
       //获的子类的具体结构 反射

        //1.获取请求的路径
        String uri = req.getRequestURI();
        System.out.println("当前访问地址： " + uri);// /user/login

        //2.截取uri的最后一个单词作为方法名
        String methodName = uri.substring(uri.lastIndexOf("/") + 1);
        System.out.println("methodName = " + methodName);

        //3.用截取的方法名通过反射获取改方法对象
        //3.1 获取方法所在类的字节码文件
        Class<? extends BaseServlet> cla = this.getClass();//this表示调用当前所在方法的对象

        try {
            //3.2 获的方法对象
            Method method = cla.getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            method.setAccessible(true);//设置临时访问权限

            //4.调用方法 使用的对象是当前方法所在的对象
            method.invoke(this,req,resp);

        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }


    }


}
